package com.campus.food.controller;

import com.campus.food.config.FileUploadConfig;
import com.campus.food.model.vo.FileUploadVO;
import com.campus.food.util.FileUploadUtil;
import com.campus.food.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传控制器
 * 处理文件上传相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    /**
     * 上传商家图片
     * POST /api/upload/merchant
     */
    @PostMapping("/merchant")
    public Result<FileUploadVO> uploadMerchantImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取商家图片上传路径
        String uploadPath = fileUploadConfig.getMerchantUploadPath();
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, "merchant", request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 上传食品图片
     * POST /api/upload/food
     */
    @PostMapping("/food")
    public Result<FileUploadVO> uploadFoodImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取食品图片上传路径
        String uploadPath = fileUploadConfig.getFoodUploadPath();
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, "food", request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 上传用户头像
     * POST /api/upload/avatar
     */
    @PostMapping("/avatar")
    public Result<FileUploadVO> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取用户头像上传路径
        String uploadPath = fileUploadConfig.getAvatarUploadPath();
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, "avatar", request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 上传评论图片
     * POST /api/upload/review
     */
    @PostMapping("/review")
    public Result<FileUploadVO> uploadReviewImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取评论图片上传路径
        String uploadPath = fileUploadConfig.getReviewUploadPath();
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, "review", request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 通用文件上传
     * POST /api/upload/common
     */
    @PostMapping("/common")
    public Result<FileUploadVO> uploadCommonFile(@RequestParam("file") MultipartFile file, 
                                              @RequestParam(value = "type", defaultValue = "common") String type,
                                              HttpServletRequest request) {
        // 根据类型确定上传路径
        String uploadPath;
        switch (type) {
            case "merchant":
                uploadPath = fileUploadConfig.getMerchantUploadPath();
                break;
            case "food":
                uploadPath = fileUploadConfig.getFoodUploadPath();
                break;
            case "avatar":
                uploadPath = fileUploadConfig.getAvatarUploadPath();
                break;
            case "review":
                uploadPath = fileUploadConfig.getReviewUploadPath();
                break;
            default:
                uploadPath = fileUploadConfig.getBasePath() + "/common";
        }
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, type, request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 批量上传文件
     * POST /api/upload/batch
     */
    @PostMapping("/batch")
    public Result<List<FileUploadVO>> uploadBatchFiles(@RequestParam("files") MultipartFile[] files,
                                                    @RequestParam(value = "type", defaultValue = "common") String type,
                                                    HttpServletRequest request) {
        if (files == null || files.length == 0) {
            return Result.badRequest("请选择要上传的文件");
        }
        
        // 根据类型确定上传路径
        String uploadPath;
        switch (type) {
            case "merchant":
                uploadPath = fileUploadConfig.getMerchantUploadPath();
                break;
            case "food":
                uploadPath = fileUploadConfig.getFoodUploadPath();
                break;
            case "avatar":
                uploadPath = fileUploadConfig.getAvatarUploadPath();
                break;
            case "review":
                uploadPath = fileUploadConfig.getReviewUploadPath();
                break;
            default:
                uploadPath = fileUploadConfig.getBasePath() + "/common";
        }
        
        List<FileUploadVO> resultList = new ArrayList<>();
        
        // 逐个上传文件
        for (MultipartFile file : files) {
            if (file != null && !file.isEmpty()) {
                // 调用通用上传方法
                FileUploadVO vo = uploadFile(file, uploadPath, type, request);
                resultList.add(vo);
            }
        }
        
        return Result.success("批量上传成功", resultList);
    }
    
    /**
     * 自定义路径上传文件
     * POST /api/upload/custom
     */
    @PostMapping("/custom")
    public Result<FileUploadVO> uploadToCustomPath(@RequestParam("file") MultipartFile file,
                                                @RequestParam("path") String customPath,
                                                HttpServletRequest request) {
        // 安全检查，防止路径遍历攻击
        if (customPath.contains("..")) {
            return Result.badRequest("路径不合法");
        }
        
        // 拼接自定义路径
        String uploadPath = fileUploadConfig.getBasePath() + File.separator + customPath;
        
        // 调用通用上传方法
        FileUploadVO result = uploadFile(file, uploadPath, "custom", request);
        
        return Result.success("上传成功", result);
    }
    
    /**
     * 删除文件
     * DELETE /api/upload
     */
    @DeleteMapping
    public Result<Boolean> deleteFile(@RequestParam("filePath") String filePath,
                                    @RequestParam(value = "type", defaultValue = "common") String type) {
        // 安全检查，防止路径遍历攻击
        if (filePath.contains("..")) {
            return Result.badRequest("路径不合法");
        }
        
        // 根据类型确定基础路径
        String basePath;
        switch (type) {
            case "merchant":
                basePath = fileUploadConfig.getMerchantUploadPath();
                break;
            case "food":
                basePath = fileUploadConfig.getFoodUploadPath();
                break;
            case "avatar":
                basePath = fileUploadConfig.getAvatarUploadPath();
                break;
            case "review":
                basePath = fileUploadConfig.getReviewUploadPath();
                break;
            default:
                basePath = fileUploadConfig.getBasePath() + "/common";
        }
        
        // 删除文件
        boolean deleted = FileUploadUtil.deleteFile(filePath, basePath);
        
        if (deleted) {
            return Result.success("文件删除成功", true);
        } else {
            return Result.error("文件删除失败");
        }
    }
    
    /**
     * 通用文件上传方法
     * 
     * @param file 上传的文件
     * @param uploadPath 上传路径
     * @param type 文件类型
     * @param request HTTP请求
     * @return 文件上传结果
     */
    private FileUploadVO uploadFile(MultipartFile file, String uploadPath, String type, HttpServletRequest request) {
        // 上传文件
        String relativePath = FileUploadUtil.uploadFile(file, uploadPath, fileUploadConfig);
        
        // 构建返回结果
        FileUploadVO vo = new FileUploadVO();
        vo.setOriginalFilename(file.getOriginalFilename());
        
        // 获取存储的文件名
        String filename = relativePath.substring(relativePath.lastIndexOf(File.separator) + 1);
        vo.setFilename(filename);
        
        // 设置文件路径
        vo.setFilePath(relativePath);
        
        // 构建文件URL
        String basePath = request.getScheme() + "://" + request.getServerName();
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            basePath += ":" + request.getServerPort();
        }
        basePath += request.getContextPath();
        
        // 生成文件访问URL
        String fileUrl = basePath + "/api/file/" + type + "/" + relativePath.replace(File.separator, "/");
        vo.setFileUrl(fileUrl);
        
        // 设置文件大小
        vo.setFileSize(file.getSize());
        
        // 设置文件类型
        vo.setFileType(file.getContentType());
        
        return vo;
    }
} 